from struct import *
import os.path
rootdir = 'F:/new_tdx/vipdoc/cw'
filename = './gpcw.txt'
hexfilename = './gpcw.hex'
list = os.listdir(rootdir) 
fh = open(filename, 'w')
hexfh = open(hexfilename, 'wb')
for i in range(0,len(list)):
    path = os.path.join(rootdir,list[i])
    if os.path.isfile(path) and 'gpcw' in path and 'dat' in path:
				print("%s" % (path))
				cw_file = open(path, 'rb')
				header_size = calcsize("<3h1H3L")
				stock_item_size = calcsize("<6s1c1L")
				data_header = cw_file.read(header_size)
				stock_header = unpack("<3h1H3L", data_header)
				max_count = stock_header[3]
				date = path[path.find('gpcw')+4:path.find('.dat')]
				for stock_idx in range(0, max_count):
				    cw_file.seek(header_size+stock_idx*calcsize("<6s1c1L"))
				    si = cw_file.read(stock_item_size)
				    stock_item = unpack("<6s1c1L", si)
				    code = stock_item[0].decode().encode("ascii")
				    foa = stock_item[2]
				    cw_file.seek(foa)
				    info_data = cw_file.read(calcsize('<286f'))
				    data_size = len(info_data)
				    cw_info = unpack('<286f', info_data)
				    fh.write(code+'\t'+date+'\t'+str(cw_info).strip('()').replace(',', '\t')+'\n')
				    a = pack(str(len(code))+"si",code,int(date))
				    hexfh.write(a)
				    hexfh.write(info_data)
        		#a = pack("i", date)
        		#hexfh.write(a)
				    #print("%s, %s" % (code, str(cw_info).strip('()').replace(',', '\t')))
				    #print('\t'.join(cw_info))
				    #for j in range(0,len(cw_info)):
				    #		print(cw_info[j])
				    #break
    
fh.close()
hexfh.close()
